﻿#include "ClosableListWidget.h"
#include "ClosableListWidgetItem.h"
#include <QEvent>
#include <QMouseEvent>
#include <QDebug>

ClosableListWidget::ClosableListWidget(QWidget *parent)
    : FListWidget(parent)
{
    connect(this, &QListWidget::itemActivated, this, &ClosableListWidget::onParentItemActivated);
    connect(this, &QListWidget::itemClicked, this, &ClosableListWidget::onParentItemClicked);
}

ClosableListWidgetItem* ClosableListWidget::addItem(const QString &text)
{
    return insertItem(count(), text);
}

ClosableListWidgetItem* ClosableListWidget::addItem(const QIcon &icon, const QString &text)
{
    return insertItem(count(), icon, text);
}

ClosableListWidgetItem* ClosableListWidget::addItem(ClosableListWidgetItem *item)
{
    return insertItem(count(), item);
}

ClosableListWidgetItem* ClosableListWidget::insertItem(int row, const QString &text)
{
    return insertItem(row, QIcon(), text);
}

ClosableListWidgetItem* ClosableListWidget::insertItem(int row, const QIcon &icon, const QString &text)
{
    ClosableListWidgetItem *item = new ClosableListWidgetItem(this);
    item->setText(text);
    item->setIcon(icon);

    return insertItem(row, item);
}

ClosableListWidgetItem* ClosableListWidget::insertItem(int row, ClosableListWidgetItem *item)
{
    QListWidgetItem *pi = new QListWidgetItem(this);
    pi->setSizeHint(item->size());

    QListWidget::insertItem(row, pi);
    setItemWidget(pi, item);

    // 连接关闭请求信号
    connect(item, &ClosableListWidgetItem::closeRequested, this, &ClosableListWidget::onItemCloseRequested);

    return item;
}

void ClosableListWidget::closeItem(int row)
{
    if (row < 0 || row >= count()) return;

    ClosableListWidgetItem *widget = item(row);

    if (widget) {
        emit itemRemoved(widget->text());
        delete takeItem(row);
    }
}

ClosableListWidgetItem *ClosableListWidget::item(int row) const
{
    QListWidgetItem* pi = QListWidget::item(row);
    ClosableListWidgetItem *widget = qobject_cast<ClosableListWidgetItem*>(itemWidget(pi));
    return widget;
}

int ClosableListWidget::row(ClosableListWidgetItem *item) const
{
    for (int i = 0; i < count(); ++i) {
        ClosableListWidgetItem *widget = this->item(i);

        if (widget == item) {
            return i;
        }
    }
    return -1;
}

void ClosableListWidget::onItemCloseRequested()
{
    // 找到发送信号的 widget 对应的 item
    for (int i = 0; i < count(); ++i) {
        ClosableListWidgetItem *widget = item(i);

        if (widget && widget == sender()) {
            emit itemCloseRequested(i);
            break;
        }
    }
}

void ClosableListWidget::onParentItemActivated(QListWidgetItem *item)
{
    ClosableListWidgetItem *widget = qobject_cast<ClosableListWidgetItem*>(itemWidget(item));
    emit itemActivated(widget);
}

void ClosableListWidget::onParentItemClicked(QListWidgetItem *item)
{
    ClosableListWidgetItem *widget = qobject_cast<ClosableListWidgetItem*>(itemWidget(item));
    emit itemClicked(widget);
}
